var canvas;
var ctx;
var width, height;
var dartBackground = "#007226";
var colorMaster1 = "#e34c37";
var colorMaster2 = "#007e56";
var colorNormal1 = "#f3e4c5";
var colorNormal2 = "#010101";
var colorGrid = "#999999";
var gamer = null;
var gamerIndex = 0;
var actGamerID = null;
var throwCount = 0;

var countArray  = [6,10,15,2,17,3,19,7,16,8,11,14,9,12,5,20,1,18,4,13];

var radOuter, radDouble, radTripleOuter, radTripleInner, radBull, radDoubleBull = 0;

// Converts from degrees to radians.
Math.radians = function(degrees) {
    return degrees * Math.PI / 180;
};

Math.degrees = function(radians) {
    return radians * (180)/Math.PI;
};

function init() {
	canvas = document.getElementById('dartcanvas');
	if(canvas!=null) {
		ctx = canvas.getContext("2d");
		
		width = jQuery(canvas).width();
		height = jQuery(canvas).height();
		
		clear();
		generateDartGrid();
		drawNumbers();
		generateOverlay();
	}
}

function initMousePointer() {
	if(canvas) {
		canvas.addEventListener('mouseup', mouseClick, true);
	}
}

function mouseClick(e) {
	var pX, py;
	pX = e.pageX - canvas.offsetLeft;
	pY = e.pageY - canvas.offsetTop;
	center = canvas.width/2;
	distanceX = Math.abs(center - pX);
	distanceY = Math.abs(center - pY);
	
	centerP = {'x': center, 'y': center};
	hitP = {'x':pX, 'y':pY};
	offP = {'x': 0, 'y': radius};
	
	angle = Math.degrees(getAngle(offP, hitP, centerP));
	angle = angle - 180;
	if(center < pY) {
		angle = Math.abs(angle);
	} else {
		angle = 360 + angle;
	}

	distanceC = Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
	
	result = getDartValue(angle, distanceValue(distanceC));
	console.log(result);
	writeToValues(result);
}

function writeToValues(value) {
	data = {};
	gametype = jQuery('select[name="game_id"] option:selected').val();
	nextGameID = jQuery('#nextGameID').val();
	if(!gamer) {
		gamer = [];
		jQuery('.gridtable td input[type="checkbox"]:checked').each(function() {
			id = parseInt($(this).val());
			if(id) {
				gamer.push(id);
			}
		});
		actGamerID = gamer[gamerIndex];
	}
	
	//split value to write
	score = value.split('_')[0];
	score_multiplier = value.split('_')[1];

	if(gametype && actGamerID && nextGameID && score && score_multiplier) {
		data.game_uuid = nextGameID;
		data.game_id = gametype;
		data.player_id = actGamerID;
		data.score = score;
		data.score_multiplier = score_multiplier;
		$.ajax({
			url: "dartboard_db.php",
			type: "GET",
			data: data,
			success: function() {
				loadGameData(nextGameID);
				loadGameResult(nextGameID);
			}
		});
		
		throwCount++;
	}
	
	// get actual gamer
	if (throwCount == 3) {
		throwCount = 0;
		gamerIndex < (gamer.length-1) ? gamerIndex++ : gamerIndex = 0;
	}
	actGamerID = gamer[gamerIndex];	
}

function loadGameData(game_uuid) {
	get = {};
	get.game_uuid = game_uuid;
	$.ajax({
		url: "game_db_view.php",
		type: "GET",
		data: get,
		success: function(response) {
			$('.data_results').html(response);
				$('.data_results .throwRemover').click(function() {
				_this = $(this);
				throwID = _this.val();
				gameUUID = _this.attr('data-gameuuid');
				if(throwID && gameUUID) {
					removeThrow(throwID, gameUUID);
				}
			});
		}
	});
}

function loadGameResult(game_uuid) {
	get = {};
	get.game_uuid = game_uuid;
	$.ajax({
		url: "game_result_view.php",
		type: "GET",
		data: get,
		success: function(response) {
			$('.data_ranking').html(response);
			$('.data_ranking .gridtable td.playername').removeClass('active');
			$('.data_ranking .gridtable td.player'+actGamerID).addClass('active');
		}
	});
}

function removeThrow(throwID, gameUUID) {
	removal = {};
	removal.throwID = throwID;
	$.ajax({
		url: "throw_remove.php",
		type: "GET",
		data: removal,
		success: function(response) {
			loadGameData(gameUUID);
			loadGameResult(nextGameID);
		}
	});
}

function getDartValue(angle, multiplier ) {
	var hitCount = 0;
	for(i = 0; i < countArray.length; i++) {
		
	}
	switch(multiplier) {
		case 50:
			return '25_2';
		case 25:
			return '25_1'
		case 3:
			return getNumberForAngle(angle) + '_3';
		case 2:
			return getNumberForAngle(angle) + '_2';
		case 1:
			return getNumberForAngle(angle) + '_1';
		case 0:
			return '0_0';
	}
}

function getNumberForAngle(angle) {
	var retValue = '';
	
	calcAngle = angle + 9;
	if(calcAngle > 360) {
		calcAngle = calcAngle - 360;
	}
	
	for(i=1;i<21;i++) {
		if (calcAngle < i*18) {
			return countArray[i-1];
		}
	}
	
	return retValue;
}

function distanceValue(distance) {
	if( distance < radDoubleBull) {
		return 50;
	} else if(distance > radDoubleBull && distance < radBull) {
		return 25;
	} else if(distance > radBull && distance < radTripleInner) {
		return 1;
	} else if(distance > radTripleInner && distance < radTripleOuter) {
		return 3;
	} else if(distance > radTripleOuter && distance < radDouble) {
		return 1;
	} else if(distance > radDouble && distance < radOuter) {
		return 2;
	} else {
		return 0;
	}
}

function getAngle(p1,p2,center) {
    var p1c = Math.sqrt(Math.pow(center.x-p1.x,2)+
                        Math.pow(center.y-p1.y,2)); // p1->c (b)   
    var p2c = Math.sqrt(Math.pow(center.x-p2.x,2)+
                        Math.pow(center.y-p2.y,2)); // p2->c (a)
    var p1p2 = Math.sqrt(Math.pow(p2.x-p1.x,2)+
                         Math.pow(p2.y-p1.y,2)); // p1->p2 (c)
    return Math.acos((p2c*p2c+p1c*p1c-p1p2*p1p2)/(2*p2c*p1c));
}

function clear() {
	canvas.width = width;
	canvas.height = height;
	
    if(canvas.width < canvas.height) {
        canvas.height = canvas.width;
    } else {
        canvas.width = canvas.height;
    }
    
    ctx.save();
    ctx.fillStyle = dartBackground;
    ctx.fillRect(0,0,width,height);
    ctx.restore();
}

function generateDartGrid() {
    radius = canvas.width/2;
    center = [radius,radius];
	//console.log('center:' + center)
	
	radOuter = radius - radius/10;
	radDouble = radOuter - radius/21;
	radTripleOuter = radOuter - (radOuter*0.37);
	radTripleInner = radTripleOuter - radOuter/21;
	radBull = radOuter-radOuter*0.9;
	radDoubleBull = radOuter-radOuter*0.96;
	
	drawCircle(radius, "#000000");
	drawGrid(radOuter, true, colorMaster1, colorMaster2);
	drawGrid(radDouble, false, colorNormal1, colorNormal2);
	drawGrid(radTripleOuter, true, colorMaster1, colorMaster2);
	drawGrid(radTripleInner, false, colorNormal1, colorNormal2);
	drawCircle(radBull, colorMaster2);
	drawCircle(radDoubleBull, colorMaster1);
	
	//console.log(radOuter, radTripleOuter, radTripleInner, radBull, radDoubleBull);
}

function generateOverlay() {
	ol = jQuery('.dartomat .overlay')[0];
	jQuery(ol).css('width', canvas.width).css('height', canvas.height).css('line-height', canvas.height+'px');	
}

function drawGrid(radius, even, color1, color2) {   
    grid = 360 / 20;
    startAngle = 0 + grid / 2;
    while(startAngle<369) {
        
        toAngle = startAngle + grid;
        ctx.beginPath();
        ctx.arc(center[0], center[0], radius, Math.radians(startAngle), Math.radians(toAngle), false);
		ctx.lineTo(center[0], center[0]);
		ctx.closePath();
		ctx.lineWidth = 1;
		ctx.strokeStyle = colorGrid;
        if(even) {
            ctx.fillStyle = color1;
        } else {
            ctx.fillStyle = color2;
        }
        ctx.fill();
		ctx.stroke();
               
        startAngle = toAngle;
        even = !even;
    }
}

function drawCircle(radius, color) {
	ctx.beginPath();
	ctx.arc(center[0], center[0], radius, Math.radians(0), Math.radians(360), false);
	ctx.closePath();
	ctx.lineWidth = 2;
	ctx.strokeStyle = colorGrid;
	ctx.fillStyle = color;
	ctx.fill();
	ctx.stroke();
}

function drawNumbers() {
	var fontHeight = radius - radOuter - 10;
	ctx.beginPath();
	ctx.fillStyle = "white";
	ctx.font = "bold "+ fontHeight + "px Arial";
	
	var digitCount = 20;
	var digitRad = radOuter + fontHeight/2;
	
	for (var i = 0; i < digitCount; ++i) {
	  ctx.beginPath();
	  var angle = i*2*Math.PI/digitCount;
	  var x = center[0] + Math.cos(angle) * digitRad;
	  var y = center[0] + Math.sin(angle) * digitRad;
	  ctx.textAlign = "center";
	  ctx.fillText(countArray[i], x+10, y+10, 50);
	  ctx.fillStyle = "white";
	  ctx.fill();
	}
}

jQuery(document).ready(function() {
	init();
	initMousePointer();
});

jQuery(window).resize(function() {
	init();
});